import store from '@/store/index'
import io from "@hyoga/uni-socket.io";
import { showToast } from "@/common/api.js"
let socket = null;
const CONNECT_EVENT = 'connect';
const DISCONNECT_EVENT = 'disconnect';
const RECONNECT_EVENT = 'reconnect';
const HEARTBEAT_EVENT = 'heartbeat';

// 封装websocket连接对象，包含重连和心跳功能
function createSocket(url, options) {

  if (!socket) {
    socket = io(url, options);
    socket.on(CONNECT_EVENT, () => {
      console.log('WebSocket connected111');
    });
    socket.on(DISCONNECT_EVENT, () => {
      console.log('WebSocket disconnected222');
      showToast("加入房间失败、断开连接")
      uni.$u.route(`/pages/index/index`);
      store.dispatch('changeNavBar', 'home')
    });
    socket.on(RECONNECT_EVENT, () => {
      console.log('WebSocket reconnected333');
    });
    socket.on(HEARTBEAT_EVENT, () => {
      console.log('WebSocket heartbeat received444');
    });

  }
  return socket;
}

export default createSocket;